package com.cskaoyan.service;


import com.cskaoyan.bean.baseresultVO.BaseData;
import com.cskaoyan.bean.baseresultVO.BaseParam;
import com.cskaoyan.bean.domain.Keyword;
import com.cskaoyan.bean.domain.KeywordExample;
import com.cskaoyan.mapper.KeywordMapper;
import com.cskaoyan.utils.MyUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class KeywordServiceImpl implements KeywordService {

    @Resource
    KeywordMapper mapper;

    @Override
    public BaseData getList(BaseParam param, String keyword, String url) {
        PageHelper.startPage(param.getPage(), param.getLimit());
        KeywordExample example = new KeywordExample();
        KeywordExample.Criteria criteria = example.createCriteria();


        if (keyword != null && keyword.trim().equals("")) {
            criteria.andKeywordLike("%" + keyword.trim() + "%");
        }
        if (url != null && !url.trim().equals("")) {
            criteria.andUrlLike("%" + url.trim() + "%");
        }
        criteria.andDeletedEqualTo(false);

        example.setOrderByClause(param.getSort() + " " + param.getOrder());

        List<Keyword> keywordList = mapper.selectByExample(example);

        PageInfo<Keyword> pageInfo = new PageInfo<>(keywordList);
        Integer total = MyUtils.getInteger(pageInfo.getTotal());
        return new BaseData(pageInfo.getPageNum(), pageInfo.getSize(), total, pageInfo.getPages(), keywordList);
    }

    @Override
    public Keyword createKeyword(Keyword keyword) {
        Date date = new Date();

        keyword.setUpdateTime(date);
        keyword.setAddTime(date);

        // useGeneratedKeys="true" keyProperty="id" keyColumn="id"
        mapper.insertSelective(keyword);

        return keyword;
    }

    @Override
    public void deleteKeyword(Keyword keyword) {
        keyword.setDeleted(true);
        mapper.updateByPrimaryKeySelective(keyword);
    }

    @Override
    public Keyword updateKeyword(Keyword keyword) {
        Date date = new Date();

        keyword.setUpdateTime(date);

        mapper.updateByPrimaryKeySelective(keyword);

        return keyword;
    }


}
